package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.NoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void save(Notice notice) {
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        for (Notice notice : notices) {
            Notice n = noticeMapper.selectByEidAndNid(employee.getId(), notice.getId());
            if (n != null) {
                notice.setReaded(true);
            }
        }
        return new PageInfo<Notice>(notices);
    }

    /**
     * 标记已读
     *
     * @param id
     */
    @Override
    public void read(Long id) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        Notice n = noticeMapper.selectByEidAndNid(employee.getId(), id);
        if (n == null) {
            noticeMapper.insertRelation(employee.getId(), id);
        }
    }

    /**
     * 新增或保存
     *
     * @param notice
     */
    @Override
    public void saveOrUpdate(Notice notice) {
        if (notice.getId() != null) {
            noticeMapper.updateByPrimaryKey(notice);
        } else {
            notice.setIssuer((Employee) SecurityUtils.getSubject().getPrincipal());
            notice.setPubdate(new Date());
            noticeMapper.insert(notice);
        }
    }
}
